//
//  ProductNew.m
//  Trading365
//
//  Created by Jason on 12-3-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CustomerNew.h"
#import "QuotEditCell.h"
#import "QuotSelectList.h"
#import "RoundedRectImageCreater.h"
#import "DHCUtil.h"

@implementation CustomerNew
@synthesize table;

static NSMutableDictionary *InfoNameDict;
static NSMutableDictionary *InfoCodeDict;
static UIImage *imageData;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title=INFO_STRING_CUSTOMER_ADD;
    [self.table setBackgroundColor:BACKGROUND_COLOR];
    
    guid=[[NSString alloc] initWithString:[GUID getGUIDString]];
    self.navigationItem.rightBarButtonItem.enabled=YES;
    
    NSArray *title_array = [[NSArray alloc] initWithObjects:@"客户图片",@"客户编码",@"客户名称",@"客户类型",@"客户来源",@"信用等级",@"电话",@"公司地址",nil];
    self.InfoListTitle = title_array; 
    [title_array release];

    NSArray *name_title = [[NSArray alloc] initWithObjects:@"",nil];
    self.InfoListName = name_title; 
    [name_title release];
        
    InfoNameDict = [[NSMutableDictionary alloc] initWithCapacity:0];
    InfoCodeDict = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    [InfoCodeDict setValue:@"" forKey:@"0,0"];//pic
    [InfoCodeDict setValue:@"" forKey:@"0,1"];//@"编码",
    [InfoCodeDict setValue:@"" forKey:@"0,2"];//@"简称",
    [InfoCodeDict setValue:@"" forKey:@"0,3"];//@"客户类型",
    [InfoCodeDict setValue:@"" forKey:@"0,4"];//@"客户来源",
    [InfoCodeDict setValue:@"" forKey:@"0,5"];//@"信用等级",
    [InfoCodeDict setValue:@"" forKey:@"0,6"];//@"电话",
    [InfoCodeDict setValue:@"" forKey:@"0,7"];//@"公司地址",
    
    [InfoNameDict setValuesForKeysWithDictionary:InfoCodeDict];

    imageData = [UIImage imageNamed:PIC_INFO_DEFAULT_PRODUCT];
    
    tableFrame=self.table.frame;

    [self refreshData];
    [self.table reloadData];
    
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ///////////////////////////
   
    [self.table reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {   
    [imageData release];
    
    [InfoNameDict release];
    [InfoCodeDict release];
    [table release];
    [super dealloc];
}

#pragma mark - Table view data source
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }
    else
        return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger row = [indexPath row];
    NSUInteger section = 0;
   
    if (row==0) {
        static NSString *CellIdentifier = @"InfoImageCell";
        
        InfoImageCell* cell = (InfoImageCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil){
            NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"InfoImageCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        
        cell.picture.image = imageData;
        cell.picture.userInteractionEnabled=YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(picture:)];
        [cell.picture addGestureRecognizer:singleTap];
        [singleTap release];
        
        cell.name.textAlignment =  UITextAlignmentRight;
        if (row < [self.InfoListTitle count]) {
            cell.name.text=[self.InfoListTitle objectAtIndex:row];
        }
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.backgroundView.backgroundColor = [UIColor clearColor];
        
        return cell;
    }
        
    static NSString *CellIdentifier = @"QuotEditCell";
    
    QuotEditCell* cell = (QuotEditCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"QuotEditCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        
    }
    
    [cell initEditBeginBlcok:^(NSString *txtValue,int section1,int row1)
     {
         NSString *tmp_v=[NSString stringWithString:txtValue];
         NSString *tmp_k=[NSString stringWithFormat:@"%d,%d",section1,row1];
         [InfoNameDict setValue:tmp_v forKey:tmp_k];
         [InfoCodeDict setValue:tmp_v forKey:tmp_k];
//         NSLog(@"InfoNameDict:%@",InfoNameDict);
//         NSLog(@"InfoCodeDict:%@",InfoCodeDict);
     }];
    
    // Configure the cell...
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    cell.row = row;
    cell.section = section;
    
    //allow edit
    cell.textValue.userInteractionEnabled=YES;
    cell.textValue.delegate = (id)self;
    cell.textValue.tag = row;
    
    if (row < [self.InfoListTitle count]) {
        cell.labName.text = [self.InfoListTitle objectAtIndex:row];
    }
    if (row == 3 || row == 4 || row == 5){
        cell.textValue.userInteractionEnabled=NO;
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton ;
    }
    
    if ([InfoNameDict count]>0){
        cell.textValue.text = [InfoNameDict objectForKey:[NSString stringWithFormat:@"%d,%d",section,row]];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section=0;
    NSInteger row=indexPath.row;
 
    QuotSelectList *selectList = [[QuotSelectList alloc] init];
    
    selectList.section=section;
    selectList.row=row;
    
    //2@"客户类型，
    if (row == 3){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_TYPE];  
    }
    //3客户来源，
    if (row == 4){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_ORIGIN];   
    }
    //4信用等级，
    if (row == 5){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_CREADIT];   
    }
    
    [selectList setLastSelectID:[InfoCodeDict objectForKey:[NSString stringWithFormat:@"%d,%d",section, row]]];

    [selectList initSelectBeginBlcok:^(NSString *name, NSString *code,NSString *key){
        [InfoNameDict setValue:name forKey:key];
//        NSLog(@"name=%@;code=%@,key=%@",name,code,key);
        [InfoCodeDict setValue:code forKey:key];
//        NSLog(@"InfoNameDict:%@",InfoNameDict);
//        NSLog(@"InfoSaveDict:%@",InfoCodeDict);
    }];
    
    [self.navigationController pushViewController:selectList animated:YES];
    [selectList release];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller. 
    
    NSInteger section=0;
    NSInteger row=indexPath.row;
    
    QuotSelectList *selectList = [[QuotSelectList alloc] init];
    
    selectList.section=section;
    selectList.row=row;
    
    //2@"客户类型，
    if (row == 3){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_TYPE];  
    }
    //3客户来源，
    if (row == 4){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_ORIGIN];   
    }
    //4信用等级，
    if (row == 5){
        [selectList SetInfoType:INFO_TYPE_CUSTOMER_CREADIT];   
    }
    
    [selectList setLastSelectID:[InfoCodeDict objectForKey:[NSString stringWithFormat:@"%d,%d",section, row]]];
    
    [selectList initSelectBeginBlcok:^(NSString *name, NSString *code,NSString *key){
        [InfoNameDict setValue:name forKey:key];
//        NSLog(@"name=%@;code=%@,key=%@",name,code,key);
        [InfoCodeDict setValue:code forKey:key];
//        NSLog(@"InfoNameDict:%@",InfoNameDict);
//        NSLog(@"InfoSaveDict:%@",InfoCodeDict);
    }];
    
    [self.navigationController pushViewController:selectList animated:YES];
    [selectList release];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (indexPath.row > 2 && indexPath.row < 6)
        return indexPath;

    return nil;
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex > 1)
        return;
    
    int type=buttonIndex;
    if ([[InfoType share] IsSimulator])
        type = 1;
    
    ProductTakePict *picture = [[ProductTakePict alloc] init];
    [picture setBusinessID:guid];
    [picture setBusinessType:@"011"];//FileBusinessType011	FileBusinessType	011	客户图片
    [picture setMyTitle:@"添加客户图片"];
    [picture setFlagCameraPhotos:type];
    [picture initPictureBeginBlcok:^(NSDictionary *imgInfo,int typeFlag) {
        UIImage *newImage0 = [RoundedRectImageCreater createRoundedRectImage:[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size: [[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size] ];
        if (typeFlag == 0){
//            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage scale:1.0 orientation:UIImageOrientationRight];
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage];

        }else{
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage];
        }
        
    }];
    [self.navigationController pushViewController:picture animated:YES];
    
    [picture release];
    
}


#pragma mark - text delegate
//该方法为点击输入文本框要开始输入是调用的代理方法：就是把view上移到能看见文本框的地方
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    //[UIView setAnimationDuration:0.30]; 
    self.table.frame = CGRectMake(tableFrame.origin.x,tableFrame.origin.y,tableFrame.size.width,tableFrame.size.height - 216 - 49-20);

    [self.table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:textField.tag inSection:0]
                      atScrollPosition:UITableViewScrollPositionBottom
                              animated:NO];  
    
    //[UIView commitAnimations];

}
    
//该方法为完成输入后要调用的代理方法：虚拟键盘隐藏后，要恢复到之前的文本框地方
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    //[UIView setAnimationDuration:0.30]; 
    self.table.frame = tableFrame;
    //[UIView commitAnimations];

}

#pragma mark - 
#pragma mark - my func

-(void) OnPreExcute
{
    //    [super OnPreExcute];
}

-(void) DoInBackground
{
    [self.table reloadData];
}

-(void) OnPostExcute
{
    //    [super OnPostExcute];
}

-(void)refreshData
{    
//    [[[TaskManager Share] GetTaskByType:NewProduct Delegate:self] Excute];
}

-(void)picture:(id)sender{
    UIActionSheet *styleAlert = [[UIActionSheet alloc] 
                                 initWithTitle:@""
                                 delegate:(id)self 
                                 cancelButtonTitle:@"取  消"  //2
                                 destructiveButtonTitle:nil
                                 otherButtonTitles: @"照相机",//0
                                 @"相册",                     //1
                                 nil];
    [styleAlert showFromTabBar:self.tabBarController.tabBar];
    [styleAlert release];
    
}

-(void)save{
    NSString *alert=@"";
    NSString *tel=@"";

    if ([[InfoCodeDict objectForKey:@"0,6"] length] > 0){
        tel = [InfoCodeDict objectForKey:@"0,6"];
        
        if (![DHCUtil checkIsNum:tel]){
            alert=@"请输入正确的电话.";
        }
    }
    
    if ([[InfoCodeDict objectForKey:@"0,5"] length] < 1)
        alert=@"请选择信用等级.";

    if ([[InfoCodeDict objectForKey:@"0,4"] length] < 1)
        alert=@"请选择客户来源.";
    
    if ([[InfoCodeDict objectForKey:@"0,3"] length] < 1)
        alert=@"请选择客户类型.";
    
    if ([[InfoCodeDict objectForKey:@"0,2"] length] < 1)
        alert=@"请输入客户名称.";

    if ([[InfoCodeDict objectForKey:@"0,1"] length] < 1)
        alert=@"请输入客户编码.";

    if ([alert length]>0){
        UIAlertView *alertview=[[UIAlertView alloc] initWithTitle:@"提示" message:alert delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
        [alertview release];
        return;
    }    
    
    NSString *tmp_img_id=@"";
    
    NSMutableDictionary *tmpDict=[[InfoType share] GetTranValueDict];
    if (tmpDict != nil){
        if ([tmpDict count] > 0){
            NSLog(@"tmpDict=%@",tmpDict);
            tmp_img_id = [tmpDict objectForKey:@"file_path"];
        }
    }

    XmlRpc *xml = [[XmlRpc alloc] init];
    NSMutableDictionary *tmp;
    tmp = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
//           [GUID getGUIDString],@"id",
           guid,@"id",
           tmp_img_id,@"default_image_id",//GUID getGUIDString
           [InfoCodeDict objectForKey:@"0,1"],@"customer_code",
           [InfoCodeDict objectForKey:@"0,2"],@"customer_short_name",
           [InfoCodeDict objectForKey:@"0,2"],@"customer_name_cn",
           [InfoCodeDict objectForKey:@"0,3"],@"customer_type_id",
           [[Session share] getMemberID],@"employee_id",
           [InfoCodeDict objectForKey:@"0,4"],@"customer_origin",
           [InfoCodeDict objectForKey:@"0,5"],@"creadit_quota_id",
           [InfoCodeDict objectForKey:@"0,6"],@"telphone",
           [InfoCodeDict objectForKey:@"0,7"],@"address",
           [[Session share] getMemberID],@"creator",
           [DHCUtil getCurrentDateTime],@"create_time",nil];
//           [DHCUtil getCurrentDateTime],@"create_time",nil];
    
    NSLog(@"tmp=%@",tmp);
    
    [xml SaveNewCustomer:tmp];
    
    [tmp release];
    [xml release];
    
    [myToast showWithText:@"Save OK."];
    self.navigationItem.rightBarButtonItem.enabled=NO;
    [[InfoType share] SetFlagFreshView:INFO_TYPE_VIEW_REFRESH]; 
}

@end
